package luanluan.control.managers 
{
	import flash.display.DisplayObject;
	import flash.events.MouseEvent;
	import flash.geom.Rectangle;
	import flash.utils.Dictionary;
	import luanluan.utils.ArrayUtils;
	
	/**
	 * 鼠标拖拽管理器
	 * @author luanluan
	 */
	public class DragManager  
	{
		//	*显示对象列表
		private var _objList:Vector.<DisplayObject> = new Vector.<DisplayObject>();
		//	*限制对象字典
		private var _limitDic:Dictionary = new Dictionary();
		
		/**
		 * 添加需要拖动的对象
		 * @param	displayObj	显示对象
		 * @param	limit		是否限制不允许超出舞台
		 */
		public function addDragItem(displayObj:DisplayObject , limit:Boolean = true):void
		{
			if (!_objList.length && displayObj)
			{
				StageManager.instance.stage.addEventListener(MouseEvent.MOUSE_MOVE , mouseMoveHandle);
			}
			ArrayUtils.addElement(_objList , displayObj);
			_limitDic[displayObj] = limit;
		}
		
		/**
		 * 移除对象
		 * @param	displayObj
		 */
		public function removeDragItem(displayObj:DisplayObject):void
		{
			ArrayUtils.removeElement(displayObj , _objList);
			delete _limitDic[displayObj];
			if (!_objList.length)
			{
				StageManager.instance.stage.removeEventListener(MouseEvent.MOUSE_MOVE , mouseMoveHandle);
			}
		}
		
		private function mouseMoveHandle(e:MouseEvent):void 
		{
			var len:int = _objList.length;
			for (var i:int = 0; i < len; i++) 
			{
				var item:DisplayObject = _objList[i];
				item.x = StageManager.instance.stage.mouseX;
				item.y = StageManager.instance.stage.mouseY;
				if (_limitDic[item])
					limit(item);
			}
		}
		
		private function limit(item:DisplayObject):void 
		{
			var rect:Rectangle = item.getBounds(item);
			rect.width *= item.scaleX;
			rect.height *= item.scaleY;
			if (item.x - rect.x < 0)
				item.x = rect.x;
			if (item.y - rect.y < 0)
				item.y = rect.y;
			if (item.x + rect.width > StageManager.instance.stage.stageWidth)
				item.x = StageManager.instance.stage.stageWidth - rect.width;
			if (item.y + rect.height > StageManager.instance.stage.stageHeight)
				item.y = StageManager.instance.stage.stageHeight - rect.height;
		}
		
		private static var _instance:DragManager;
		
		public function DragManager(single:Single)
		{ 
			if ( !single )
				throw(new Error( "请使用静态instance获取单例引用" ) );
		} 
		
		public static function get instance():DragManager 
		{
			if(_instance == null)
			{
				_instance = new DragManager(new Single());
			}
			return _instance;
		}
	}
}
class Single{}